package com.wuyi.controller.interceptor;

import com.wuyi.controller.UsersController;
import com.zc.utils.CookieUtils;
import com.zc.utils.JSONResult;
import com.zc.utils.JsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @author 曾川
 * @version 1.0.0
 * @ClassName UserLoginInterceptor.java
 * @Description 拦截器
 * @createTime 2021年11月03日 08:36:00
 */
public class UserLoginInterceptor implements HandlerInterceptor {

    public final static Logger logger = LoggerFactory.getLogger(UserLoginInterceptor.class);

    public static final String USER_TOKEN = "user_token";


    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        logger.info("--------------进入拦截器--------------");
        //这2个从前端获取
        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        logger.info("headerUserId--------------"+userId);
        logger.info("headerUserToken--------------"+userToken);
        if(StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)){
            String uniqueToken = redisTemplate.opsForValue().get(USER_TOKEN + ":" + userId);
            if(StringUtils.isBlank(uniqueToken)){
//                System.out.println("请登录...");
                returnErrorResponse(response, JSONResult.errorMsg("请登录..."));
                return false;
            }else {
                if(!uniqueToken.equals(userToken)){
//                    System.out.println("账号在异地登录...");
                    returnErrorResponse(response, JSONResult.errorMsg("账号在异地登录..."));
                    return false;
                }
            }
        }else {
            System.out.println("请登录...");
            returnErrorResponse(response, JSONResult.errorMsg("请登录后再进行此操作哦~"));
            return false;
        }
        /**
         * false :请求被拦截，被驳回，验证出现问题
         * true:请求在经过验证校验之后，是ok的，是可以放行的
         */
        return true;
    }


    public void returnErrorResponse(HttpServletResponse response,
                                    JSONResult result){
        OutputStream out = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
